package cn.wolfcode.springboot_producer.controller._01_hello;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
public class HelloController {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    //同步发送
    @GetMapping("/send")
    public Object send(String msg,String tag){
        /*MessageBuilder<String> builder = MessageBuilder.withPayload(msg);
        Message<String> message = builder.build();*/
        rocketMQTemplate.syncSend("01-springboot-hello:" + tag,msg);
        return "消息发送成功";
    }

    @GetMapping("/filterSend")
    public Object filterSend(String msg,String tag){
        HashMap<String , Object> map = new HashMap<>();
        map.put("age","18");
        map.put("weight","180");
        map.put(MessageConst.PROPERTY_KEYS,"123");
        rocketMQTemplate.convertAndSend("01-springboot-hello",msg,map);
        return "消息发送成功";
    }
    //异步发送
    @GetMapping("/asyncSend")
    public Object asyncSend(String msg){
        /*MessageBuilder<String> builder = MessageBuilder.withPayload(msg);
        Message<String> message = builder.build();*/
        rocketMQTemplate.asyncSend("01-springboot-hello", msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("发送成功");
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("发送失败");
            }
        });
        return "消息发送成功";
    }
    //一次性发送
    @GetMapping("/sendOneway")
    public Object sendOneway(String msg){
        /*MessageBuilder<String> builder = MessageBuilder.withPayload(msg);
        Message<String> message = builder.build();*/
        rocketMQTemplate.sendOneWay("01-springboot-hello",msg);
        return "消息发送成功";
    }
    @GetMapping("/sendMode")
    public Object sendMode(String msg){
        /*MessageBuilder<String> builder = MessageBuilder.withPayload(msg);
        Message<String> message = builder.build();*/
        rocketMQTemplate.sendOneWay("02-springboot-mode",msg);
        return "消息发送成功";
    }
    @GetMapping("/sendDelay")
    public Object sendDelay(String msg){
        MessageBuilder<String> builder = MessageBuilder.withPayload(msg);
        Message<String> message = builder.build();
        rocketMQTemplate.syncSend("03-springboot-delay",message,5000,3);
        return "消息发送成功";
    }
}
